const app =getApp()
Page({
  data: {
    user: [
      { cn: '选择医生', key: 'doctor_id', value: '', type: 'picker2',range:[]}, // 出生日期
    ],
    userInfo:app.globalData.user
  },
  onLoad() {
    let that = this
    // 如果有医院id
    if(that.data.userInfo.hospital_id){
      that.xInit()
    }else{
      // 渠道id

    }
  },
  xChildReload: function () {
    var pages = getCurrentPages();//当前页面栈
    if (pages.length > 1) {
      var beforePage = pages[pages.length - 2];//获取上一个页面实例对象
      beforePage.xInfo();//触发父页面中的方法
    }
  },
  xInit:function(){
    let that = this
    wx.cloud.callFunction({
      name: 'doctors',
      data: {
        action: "get_doctor_by_hospital",
        hospital_id:that.data.userInfo.hospital_id
      }
    }).then(res => {
      that.setData({
        [`user[0].range`]: res.result
      })
    })
  },
  choose:function(e){
    let that = this
    let params = e.currentTarget.dataset
    that.setData({
      [`user[${params.idx}].value`]:params.id
    })
  },
  xSubmit: function () {
    let that = this
    let user = that.data.user
    let key =0
    for (let i in that.data.user) {
      if (that.data.user[i].value === '') {
          key=key+1
      }
    }
    if(key>0){
      var firstQ = ''
      for (var i =0;i<that.data.user.length;i++) {
        if (that.data.user[i].value === '') {
          firstQ=i
          break;
        }
      }
      wx.showModal({
        title: "提示",
        content: "请确保所有内容填写正确，当前有"+ key +"项内容未填写，请检查！",
        showCancel: false,
        confirmText:'好的',
        success (res) {
          if (res.confirm) {
            wx.pageScrollTo({
              selector: '#selector'+firstQ,
            })
          }
        }
      })
      return
    }
    wx.showLoading({
      title: '保存中',
    })
    that.xUpload(user)
},

xUpload: function (data) {
    let that =this;
    let form = {}
    for (var i = 0; i < data.length; i++) {
        if (data[i].value !== '') {
            form[data[i].key] = data[i].value
        }
    }
    wx.cloud.callFunction({
        name: "user",
        data: {
            action: "edit",
            formdata: form
        }
    }).then(res => {
        wx.showToast({
            title: '保存成功',
            icon: 'none',
            success: () => {
                setTimeout(() => {
                  wx.navigateBack({
                    delta: 1,
                  })
                  that.xChildReload()
                }, 1000)
            }
        })
    })
},
  onReady() {

  },
  onShow() {

  },
  onHide() {

  },
  onUnload() {

  },
  onPullDownRefresh() {

  },
  onReachBottom() {

  },
  onShareAppMessage() {

  }
})